{"componentChunkName":"component---src-templates-post-jsx","path":"/[BOJ]1707/","result":{"data":{"site":{"siteMetadata":{"title":"SUbbb"}},"markdownRemark":{"id":"0e07a592-06ce-5e01-b5e1-95398330372e","excerpt":"문제 그래프의 정점의 집합을 둘로 분할하여, 각 집합에 속한 정점끼리는 서로 인접하지 않도록 분할할 수 있을 때, 그러한 그래프를 특별히 이분 그래프 (Bipartite Graph) 라 부른다. 그래프가 입력으로 주어졌을 때, 이 그래프가 이분 그래프인지 아닌지 판별하는 프로그램을 작성하시오. 입력 입력은 여러 개의 테스트 케이스로 구성되어 있는데, 첫째…","html":"<h2>문제</h2>\n<p>그래프의 정점의 집합을 둘로 분할하여, 각 집합에 속한 정점끼리는 서로 인접하지 않도록 분할할 수 있을 때, 그러한 그래프를 특별히 이분 그래프 (Bipartite Graph) 라 부른다.</p>\n<p>그래프가 입력으로 주어졌을 때, 이 그래프가 이분 그래프인지 아닌지 판별하는 프로그램을 작성하시오.</p>\n<h3>입력</h3>\n<ul>\n<li>입력은 여러 개의 테스트 케이스로 구성되어 있는데, 첫째 줄에 테스트 케이스의 개수 K가 주어진다. 각 테스트 케이스의 첫째 줄에는 그래프의 정점의 개수 V와 간선의 개수 E가 빈 칸을 사이에 두고 순서대로 주어진다. 각 정점에는 1부터 V까지 차례로 번호가 붙어 있다. 이어서 둘째 줄부터 E개의 줄에 걸쳐 간선에 대한 정보가 주어지는데, 각 줄에 인접한 두 정점의 번호 u, v (u ≠ v)가 빈 칸을 사이에 두고 주어진다. </li>\n</ul>\n<h3>출력</h3>\n<ul>\n<li>K개의 줄에 걸쳐 입력으로 주어진 그래프가 이분 그래프이면 YES, 아니면 NO를 순서대로 출력한다.</li>\n</ul>\n<h3>📍 <strong>Logic</strong></h3>\n<deckgo-highlight-code language=\"java\" terminal=\"carbon\" theme=\"a11y-dark\" line-numbers=\"true\"  >\n          <code slot=\"code\">class Graph {\n    final List&lt;Integer&gt;[] graph;\n    final int[] Binary = { -1, 1 };\n    int[] discovered;\n    boolean isBinaryGraph = true;\n    int toggle = 0;\n\n    public Graph(int size) {\n        this.graph = new ArrayList[size+1];\n        discovered = new int[size+1];\n\n        for (int i = 0; i &lt;= size; i++) {\n            graph[i] = new ArrayList&lt;&gt;();\n        }\n    }\n}</code>\n        </deckgo-highlight-code>\n<ul>\n<li>그래프의 정보를 저장하기 위한 클래스</li>\n</ul>\n<deckgo-highlight-code language=\"java\" terminal=\"carbon\" theme=\"a11y-dark\" line-numbers=\"true\"  >\n          <code slot=\"code\">public boolean solution() {\n    for (int i=1; i &lt; graph.length; i++) {\n        if (graph[i].size() &gt; 0 &amp; discovered[i] == 0) {\n            isBinaryGraph = this.bfs(i);\n            if (!isBinaryGraph)\n                break;\n        }\n    }\n    return this.isBinaryGraph;\n}</code>\n        </deckgo-highlight-code>\n<ul>\n<li>\n<p>인접 정점 정보가 있고, 아직 방문하지 않은 정점에 대해 <em>BFS</em> 를 수행</p>\n<ul>\n<li>정점의 방문 여부는 (0: 미방문), (-1: 1그룹), (1: 2그룹)</li>\n</ul>\n</li>\n<li>이분 그래프인지를 저장하는 <code class=\"language-text\">isBinaryGraph</code> 에 <code class=\"language-text\">false</code> 가 나오면 더 이상의 탐색을 종료하고 이를 반환</li>\n<li><code class=\"language-text\">false</code> 가 계속 나오지 않으면 이분 그래프이므로 초기값인 <code class=\"language-text\">true</code> 가 반환</li>\n</ul>\n<deckgo-highlight-code language=\"java\" terminal=\"carbon\" theme=\"a11y-dark\" line-numbers=\"true\"  >\n          <code slot=\"code\">public boolean bfs(int parent) {\n    Queue&lt;Integer&gt; q = new LinkedList&lt;&gt;();\n    q.add(parent);\n    while (!q.isEmpty()) {\n        int now = q.poll();\n        if (discovered[now] == 0) { discovered[now] = Binary[toggle]; }\n        toggle = (discovered[now] == -1 ? 1 : 0);\n        for (int tmp : graph[now]) {\n            if (discovered[tmp] == 0) {\n                q.add(tmp);\n                discovered[tmp] = Binary[toggle];\n            } else if (discovered[tmp] == discovered[now])\n                return false;\n        }\n    }\n    return true;\n}</code>\n        </deckgo-highlight-code>\n<ul>\n<li><code class=\"language-text\">Queue</code> 를 이용하여 <strong>BFS</strong> 수행</li>\n<li>방문하지 않은 정점은 방문 여부 값을 가지고 있는 <code class=\"language-text\">Binary</code> 배열과 <code class=\"language-text\">toggle</code> 변수로 <strong>setting</strong></li>\n<li><strong>BFS 단계별 서로 다른 방문 값 저장</strong></li>\n<li>다음 방문할 정점이 <strong>이미 방문</strong>했고, 현재 방문 정점과 <strong>같은 방문 값</strong>을 가진다면 <strong>이분 그래프 불가</strong></li>\n</ul>\n<h3>📄 <strong>틀린 CODE</strong></h3>\n<details>\n  <summary>코드 보기/접기💫</summary>\n    <div markdown=\"1\">\n<deckgo-highlight-code  terminal=\"carbon\" theme=\"a11y-dark\" line-numbers=\"true\"  >\n          <code slot=\"code\">import java.util.ArrayList;\nimport java.util.Scanner;\n\nclass Graph {\n    private final ArrayList&lt;ArrayList&lt;Integer&gt;&gt; graph;\n    private int[] discovered;\n    private boolean oddCycle = false;\n    private int dis;\n\n    public Graph(int size) {\n        this.graph = new ArrayList&lt;&gt;();\n\n        for (int i = 0; i &lt;= size; i++) {\n            graph.add(new ArrayList&lt;&gt;());\n        }\n    }\n\n    public void DoubleAdd(int x, int y) {\n        graph.get(x).add(y);\n        graph.get(y).add(x);\n    }\n\n    public boolean isOddCycle(int s, int n) {\n        discovered = new int[20001];\n        dis = 1;\n        this.dfs(s, n);\n        return this.oddCycle;\n    }\n\n    public void dfs(int parent, int now) {\n        discovered[now] = dis++;\n        int size = graph.get(now).size();\n        if (size == 0) return;\n        for (int i = 0; i &lt; size; i++) {\n            int idx = graph.get(now).get(i);\n            if (discovered[idx] == 0) {\n                this.dfs(now, idx);\n            }\n            else if (idx != parent &amp;&amp; ((discovered[now] - discovered[idx])%2 == 0)) {\n                this.oddCycle = true;\n            }\n        }\n    }\n}\n\npublic class Main {\n    public static void main(String[] args) {\n        Scanner sc = new Scanner(System.in);\n        int T = sc.nextInt();\n\n        while (T &gt; 0) {\n            int v = sc.nextInt();\n            int e = sc.nextInt();\n            sc.nextLine();\n            boolean isOdd = false;\n\n            Graph g = new Graph(v);\n\n            for (int i = 0; i &lt; e; i++) {\n                String str = sc.nextLine();\n                int a = str.charAt(0) - &#39;0&#39;;\n                int b = str.charAt(2) - &#39;0&#39;;\n\n                g.DoubleAdd(a,b);\n            }\n\n            for (int i = 1; i &lt;= v; i++) {\n                isOdd = g.isOddCycle(i, i);\n                // odd가 한 번이라도 true면 이분 그래프가 될 수 없다.\n                if (isOdd)\n                    break;\n            }\n\n            if (!isOdd)\n                System.out.println(&quot;YES&quot;);\n            else\n                System.out.println(&quot;NO&quot;);\n            T-=1;\n        }\n\n        sc.close();\n    }\n}</code>\n        </deckgo-highlight-code>\n  \t</div>\n</details>\n<h3>📄 <strong>CODE</strong></h3>\n<details>\n  <summary>코드 보기/접기💫</summary>\n    <div markdown=\"1\">\n<deckgo-highlight-code  terminal=\"carbon\" theme=\"a11y-dark\" line-numbers=\"true\"  >\n          <code slot=\"code\">import java.util.*;\n\nclass Graph {\n    final List&lt;Integer&gt;[] graph;\n    final int[] Binary = { -1, 1 };\n    int[] discovered;\n    boolean isBinaryGraph = true;\n    int toggle = 0;\n\n    public Graph(int size) {\n        this.graph = new ArrayList[size+1];\n        discovered = new int[size+1];\n\n        for (int i = 0; i &lt;= size; i++) {\n            graph[i] = new ArrayList&lt;&gt;();\n        }\n    }\n\n    public void DoubleAdd(int x, int y) {\n        graph[x].add(y);\n        graph[y].add(x);\n    }\n\n    public boolean solution() {\n        for (int i=1; i &lt; graph.length; i++) {\n            if (graph[i].size() &gt; 0 &amp; discovered[i] == 0) {\n                isBinaryGraph = this.bfs(i);\n                if (!isBinaryGraph)\n                    break;\n            }\n        }\n        return this.isBinaryGraph;\n    }\n\n    public boolean bfs(int parent) {\n        Queue&lt;Integer&gt; q = new LinkedList&lt;&gt;();\n        q.add(parent);\n        while (!q.isEmpty()) {\n            int now = q.poll();\n            if (discovered[now] == 0) { discovered[now] = Binary[toggle]; }\n            toggle = (discovered[now] == -1 ? 1 : 0);\n            for (int tmp : graph[now]) {\n                if (discovered[tmp] == 0) {\n                    q.add(tmp);\n                    discovered[tmp] = Binary[toggle];\n                } else if (discovered[tmp] == discovered[now])\n                    return false;\n            }\n        }\n        return true;\n    }\n}\n\npublic class Main {\n    public static void main(String[] args) {\n        Scanner sc = new Scanner(System.in);\n        int T = sc.nextInt();\n\n        while (T &gt; 0) {\n            int v = sc.nextInt();\n            int e = sc.nextInt();\n            sc.nextLine();\n\n            Graph g = new Graph(v);\n\n            for (int i = 0; i &lt; e; i++) {\n                int a = sc.nextInt();\n                int b = sc.nextInt();\n                g.DoubleAdd(a,b);\n            }\n\n            if (g.solution())\n                System.out.println(&quot;YES&quot;);\n            else\n                System.out.println(&quot;NO&quot;);\n            T-=1;\n        }\n        sc.close();\n    }\n}</code>\n        </deckgo-highlight-code>\n  \t</div>\n</details>\n<h3>✏️ <strong>Review</strong></h3>\n<ul>\n<li>논리는 \"DFS를 이용해 <strong>홀수개의 정점끼리 사이클</strong>을 이루는 경우 <strong>이분그래프가 될 수 없다</strong>\" 였고, 반례를 통해 확인했을때 얼추 맞는 것 같으나, 계속 <code class=\"language-text\">런타임 에러 (IndexOutOfBounds)</code> 가 떠서 진전이 없었다.</li>\n<li>\n<p>10번 이상의 에러로 정신이 나가버릴 것 같아 BFS를 이용하는 방법으로 바꿔보기로 했다.</p>\n<ul>\n<li>BFS를 이용하는 경우, 방문 순서로는 해결할 수 없을 것 같아 다른 방법을 고안해야 했다.</li>\n</ul>\n</li>\n<li>DFS, BFS를 확실하게 이해할 수 있었던 것 같다.</li>\n</ul>\n<deckgo-highlight-code language=\"java\" terminal=\"carbon\" theme=\"a11y-dark\" line-numbers=\"true\"  >\n          <code slot=\"code\">String str = sc.nextLine();\nint a = str.charAt(0) - &#39;0&#39;;\nint b = str.charAt(2) - &#39;0&#39;;</code>\n        </deckgo-highlight-code>\n<ul>\n<li>위 방식으로 <code class=\"language-text\">1 2</code> 형식의 숫자를 입력받으니 <code class=\"language-text\">10 12</code> 와 같은 경우 당연히 틀릴 수 밖에 없었다 ...</li>\n</ul>\n<h3>📕 출처</h3>\n<p><a href=\"https://www.acmicpc.net/problem/1707\">https://www.acmicpc.net/problem/1707</a></p>","frontmatter":{"title":"👩‍💻 1707. 이분그래프","date":"January 12, 2022","update":"January 12, 2022","tags":["그래프이론","그래프탐색","BFS","DFS"],"series":"👩‍💻 BOJ"},"fields":{"slug":"/[BOJ]1707/","readingTime":{"minutes":7.125}}},"seriesList":{"edges":[{"node":{"id":"27733333-3aad-5771-a1a1-27b4de4b4a01","fields":{"slug":"/[BOJ]2225/"},"frontmatter":{"title":"👩‍💻 2225. 합분해"}}},{"node":{"id":"548ba188-2afe-5575-b79f-107c6c65b07d","fields":{"slug":"/[BOJ]1012/"},"frontmatter":{"title":"👩‍💻 1012. 유기농 배추"}}},{"node":{"id":"0c712680-130f-5fa5-8c3b-3632dd5d1af0","fields":{"slug":"/[BOJ]1260/"},"frontmatter":{"title":"👩‍💻 1260. DFS와 BFS"}}},{"node":{"id":"0e07a592-06ce-5e01-b5e1-95398330372e","fields":{"slug":"/[BOJ]1707/"},"frontmatter":{"title":"👩‍💻 1707. 이분그래프"}}},{"node":{"id":"df12bfec-ed5c-5fc4-8442-0a4b3f9759a3","fields":{"slug":"/[BOJ]2668/"},"frontmatter":{"title":"👩‍💻 2668. 숫자 고르기"}}},{"node":{"id":"01bbb6dc-812c-5223-87c5-53bf04c0d0a6","fields":{"slug":"/[BOJ]9466/"},"frontmatter":{"title":"👩‍💻 9466. 텀 프로젝트"}}},{"node":{"id":"abc306b3-c3a6-552a-8979-e82d506b3921","fields":{"slug":"/[BOJ]2146/"},"frontmatter":{"title":"👩‍💻 2146. 다리 만들기"}}},{"node":{"id":"b3394e53-5e9a-595e-8da4-bb3debd220c0","fields":{"slug":"/[BOJ]5014/"},"frontmatter":{"title":"👩‍💻 5014. 스타트 링크"}}},{"node":{"id":"be297703-e778-5727-8019-6954bc95da3a","fields":{"slug":"/[BOJ]11559/"},"frontmatter":{"title":"👩‍💻 11559. Puyo Puyo"}}},{"node":{"id":"ddf11545-d468-5269-94b1-5daa2720e886","fields":{"slug":"/[BOJ]17471/"},"frontmatter":{"title":"👩‍💻 17471. 게리맨더링"}}},{"node":{"id":"8d77114d-fc6e-5de2-a3ca-c3b250425a56","fields":{"slug":"/[BOJ]2437/"},"frontmatter":{"title":"👩‍💻 2437. 저울"}}},{"node":{"id":"9a8942ce-552f-51ae-b304-0d0fab8f2eba","fields":{"slug":"/[BOJ]14891/"},"frontmatter":{"title":"👩‍💻 14891. 톱니바퀴"}}},{"node":{"id":"f1c04e8a-df0a-5294-949f-5f3a483cbcb0","fields":{"slug":"/[BOJ]14503/"},"frontmatter":{"title":"👩‍💻 14503. 로봇 청소기"}}},{"node":{"id":"883b6ecf-7528-5c16-92fa-edf12a64e80e","fields":{"slug":"/[BOJ]3190/"},"frontmatter":{"title":"👩‍💻 3190. 뱀"}}},{"node":{"id":"099b2576-7d05-5872-a9f0-f1ee6efd3a9a","fields":{"slug":"/[BOJ]14502/"},"frontmatter":{"title":"👩‍💻 14502. 연구소"}}},{"node":{"id":"50eef059-4e55-5f14-a9cf-fb01b6506f02","fields":{"slug":"/[BOJ]17779/"},"frontmatter":{"title":"👩‍💻 17779. 게리맨더링 2"}}},{"node":{"id":"aa67d90b-4801-574c-b225-56c23737a5e2","fields":{"slug":"/[BOJ]2579/"},"frontmatter":{"title":"👩‍💻 2579. 계단 오르기"}}},{"node":{"id":"9db6b43b-963a-5ebd-b72b-69936cf37858","fields":{"slug":"/[BOJ]14499/"},"frontmatter":{"title":"👩‍💻 14499. 주사위 굴리기"}}},{"node":{"id":"6a79cddd-dc1b-5e34-8a84-af313c37de0e","fields":{"slug":"/[BOJ]15685/"},"frontmatter":{"title":"👩‍💻 15685. 드래곤 커브"}}},{"node":{"id":"5e001d34-d985-545b-83ec-7f1c7caea286","fields":{"slug":"/[BOJ]17144/"},"frontmatter":{"title":"👩‍💻 17144. 미세먼지 안녕!"}}},{"node":{"id":"1d132410-9377-5e55-85b9-4664ff64de73","fields":{"slug":"/[BOJ]9935/"},"frontmatter":{"title":"👩‍💻 9935. 문자열 폭발"}}},{"node":{"id":"e13ff8d6-9b02-56c0-83e2-1d3144f70e1d","fields":{"slug":"/[BOJ]16472/"},"frontmatter":{"title":"👩‍💻 16472. 고냥이"}}},{"node":{"id":"0f782160-aaa9-5c54-80c0-72a15172dd16","fields":{"slug":"/[BOJ]1083/"},"frontmatter":{"title":"👩‍💻 1083. 소트"}}},{"node":{"id":"fef58615-9e18-5f50-8d09-3d1e2839342f","fields":{"slug":"/[BOJ]20922/"},"frontmatter":{"title":"👩‍💻 20922. 겹치는 건 싫어"}}},{"node":{"id":"7ca89240-c65f-5cb4-aeef-c5f1605ebd00","fields":{"slug":"/[BOJ]16172/"},"frontmatter":{"title":"👩‍💻 16172. 나는 친구가 적다(Large)"}}}]},"previous":{"fields":{"slug":"/[스프링입문]5/"},"frontmatter":{"title":"📺 5. 웹 MVC 개발"}},"next":{"fields":{"slug":"/[스프링입문]6/"},"frontmatter":{"title":"📺 6. 스프링 DB 접근 기술"}}},"pageContext":{"id":"0e07a592-06ce-5e01-b5e1-95398330372e","series":"👩‍💻 BOJ","previousPostId":"5c16c94d-5e6b-541f-b861-1bbeb45da9f8","nextPostId":"8b5e56c2-f7dd-5d13-92c4-4e18d9df605b"}},"staticQueryHashes":[]}